package smartbooks.ui.listeners;

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.SwingUtilities;
import smartbooks.exceptions.MyException;

/**
 * This class is used mainly so that the BalloonTip is hidden when the user clicks anywhere on the frame 
 * or presses a button anytime
 * @author Ankit
 */
public class CommonMouseListener implements AWTEventListener
{
    /**
     * This variable is set to 'false' when there is any valid exception and then the BalloonTip is made visible
     */
    public static boolean hideException = true;
    private Component parent;

    /**
     * This method is used to create CommonMouseListener
     * @param comp
     */
    public CommonMouseListener(Component comp)
    {
        parent = comp;
    }

    @Override
    public void eventDispatched(AWTEvent e)
    {
        if(hideException) {
            if (e instanceof MouseEvent)
            {
                if (SwingUtilities.isDescendingFrom((Component) e.getSource(), parent))
                {
                    MouseEvent m = (MouseEvent) e;
                    if (m.getID() == MouseEvent.MOUSE_PRESSED)
                    {
                        MyException.hideBalloonTip();
                    }
                }
            }

            if (e instanceof KeyEvent)
            {
                if (SwingUtilities.isDescendingFrom((Component) e.getSource(), parent))
                {
                    KeyEvent k = (KeyEvent) e;
                    if (k.getID() == KeyEvent.KEY_PRESSED)
                    {
                        MyException.hideBalloonTip();
                    }
                }
            }
        }
        
        CommonMouseListener.hideException = true;
    }
}